import React from 'react'
import { connect } from 'dva';
import {
    Button, message, Popconfirm,Modal
} from 'antd';
import {UrlConfig, weixinPush, validateSensitive, transcode,informationInfo} from '../../../services/fetch';
import { usedModule } from '../../../services/theme';
import { throttle } from '../../../utils/Date';
import './Video.scss';
import './Right.scss';
import './Footer.scss';


let adding = false;
const { confirm } = Modal;
/**
 * 连续点击判断
 */
const getAdding = () => {
    return adding;
};
const setAdding = (val,time) => {

    if (time > 0){
        setTimeout(() => {
            window.close();
            adding = val;
        }, time);
    } else{
        adding = val;
    }
};
const getCookie = (cookie_name) => {
    var allcookies = document.cookie;
    //索引长度，开始索引的位置
    var cookie_pos = allcookies.indexOf(cookie_name);

    // 如果找到了索引，就代表cookie存在,否则不存在
    if (cookie_pos != -1) {
        // 把cookie_pos放在值的开始，只要给值加1即可
        //计算取cookie值得开始索引，加的1为“=”
        cookie_pos = cookie_pos + cookie_name.length + 1;
        //计算取cookie值得结束索引
        var cookie_end = allcookies.indexOf(";", cookie_pos);

        if (cookie_end == -1) {
            cookie_end = allcookies.length;

        }
        //得到想要的cookie的值
        var value = unescape(allcookies.substring(cookie_pos, cookie_end));
    }
    return value;
}

@connect(({ add, video, theme }) => ({
    add: add,
    video: video,
    theme: theme
}))
export default class Footer extends React.PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            adding:false,
            user_name:'',
            add_information_id:0
        }
    }

    componentDidMount() {
        // console.log(getCookie('user_name'));
        let username = '';
        // if (getCookie('user_name')){
        //     username = getCookie('user_name');
        //     this.setState({
        //         user_name: getCookie('user_name')
        //     });
        // }else{
            let userinfo = localStorage.getItem('userInfo');
            //编辑名称默认为登陆管理员
            if (userinfo) {
                if (typeof userinfo === 'string'){
                    userinfo = JSON.parse(userinfo);
                }
                username = userinfo.user_name;
                this.setState({
                    user_name: username
                });
            }

        // }

        if (!username && window.location.host.indexOf('localhost') <= -1){
            message.error('登陆已过期，请重新登陆~');
            setTimeout(() => {
                if (window.top) {
                    window.top.location.href = UrlConfig;
                }else{
                    window.location.href = UrlConfig;
                }

            }, 2000);
            return;

        }


    }
    /**
     * 表单重置
     */
    reSet = () => {
        this.props.reset()
        localStorage.removeItem('moc_id')
    }

    confirm = () => {
        window.close();
    }


    addInformation =(data,id,is_update)=>{
        if(data.theme_id==''||data.theme_id==0||data.theme_id==undefined){
            return 
        }else{
            informationInfo({information_id:id}).then(res=>{
                console.log(res)
                if(res.data.code==200){
                    let params = {}
                    if(is_update){
                        params = {
                            theme_id:data.theme_id,
                            is_update:1,
                            used_modules: [{
                                used_id: id,
                                module_name: "fcinformation",
                                title: res.data.data.information_title,
                                img: res.data.data.information_img,
                                create_user:  res.data.data.create_user,
                                create_time:  res.data.data.create_time,
                                create_user_id:  res.data.data.create_user_id,
                                type:res.data.data.type,
                                thumbnail:res.data.data.thumbnail,
                                url:res.data.data.url,
                                func_name: "app\fcinformation\controller\Modulecheck::informationListInfo"
                            }]
                        }
                    }else{
                        params = {
                            theme_id:data.theme_id,
                            used_modules: [{
                                used_id: id,
                                module_name: "fcinformation",
                                title: res.data.data.information_title,
                                img: res.data.data.information_img,
                                create_user:  res.data.data.create_user,
                                create_time:  res.data.data.create_time,
                                create_user_id:  res.data.data.create_user_id,
                                type:res.data.data.type,
                                thumbnail:res.data.data.thumbnail,
                                url:res.data.data.url,
                                func_name: "app\fcinformation\controller\Modulecheck::informationListInfo"
                            }]
                        }
                    }                    
                    usedModule(params).then(res=>{
                        console.log(res)
                        // if(res.data.code!==200){
                        //     message.error(res.data.msg)
                        // }
                    })
                }
                
            })
            
            console.log(data)
        }
    }


    /**
     * 提交审核 保存草稿
     */
    submitForm = (idss) => {

        let token = localStorage.getItem('token');
        let leftForm = this.props.getLeft();
        let rightForm = this.props.getRight();
        let allForm = {};

        console.log(leftForm, rightForm)
        if (leftForm && rightForm) {
            Object.assign(allForm, leftForm, rightForm);
            console.log(allForm)
            allForm.key_words = allForm.key_words&&Array.isArray(allForm.key_words) ? allForm.key_words.join('|') : allForm.key_words;
            allForm.tag = allForm.tag&&Array.isArray(allForm.tag) ? allForm.tag.join('|') : allForm.tag;
            if(localStorage.getItem('moc_id')&&localStorage.getItem('moc_id')!=''){
                allForm.moc_id = localStorage.getItem('moc_id')
            }
            if (this.props.theme.params.class && this.props.theme.params.class == 'theme' && !this.state.add_information_id) {  //专题资讯新建
                allForm.theme_id = this.props.themeId;

                if (getAdding()){
                    return false;
                }
                setAdding(true,0);
                allForm.user_name = this.state.user_name;
                allForm.token = token;
                console.log({allForm});
                let _that = this;
                if (this.props.add.configJson.sensitivewordsSwitch){
                    validateSensitive({'content':allForm['content']}).then((res) => {

                        if (res.data.code === 500) {

                            confirm({
                                title: '存在敏感词，确认继续保存吗',
                                content: '敏感词：'+res.data.data,
                                onOk() {
                                    _that.props.dispatch({
                                        type: 'theme/addInformation', data: allForm, callback: (data) => {
                                            setAdding(false,0);
                                            if (data.code === 200){
                                                this.submitTranscode(this.props.add.transcode_data,data.data,3)
                                                message.success('保存成功!');
                                                _that.setState({
                                                    add_information_id: data.data
                                                });
                                                // this.closeWindow();
                                                if (idss === 1) {
                                                    _that.props.dispatch({
                                                        type: 'theme/getAuditVideo', data: {
                                                            status: 1,
                                                            information_ids: [data.data]
                                                        }
                                                    });
                                                    _that.closeWindow();
                                                }

                                            }

                                        }
                                    });
                                },
                                onCancel() {
                                    setAdding(false,0);
                                },
                            });
                        }else {
                            _that.props.dispatch({
                                type: 'theme/addInformation', data: allForm, callback: (data) => {
                                    setAdding(false,0);
                                    if (data.code === 200){
                                        this.submitTranscode(this.props.add.transcode_data,data.data,3)
                                        message.success('保存成功!');
                                        _that.setState({
                                            add_information_id: data.data
                                        });
                                        // this.closeWindow();
                                        if (idss === 1) {
                                            _that.props.dispatch({
                                                type: 'theme/getAuditVideo', data: {
                                                    status: 1,
                                                    information_ids: [data.data]
                                                }
                                            });
                                            _that.closeWindow();
                                        }

                                    }

                                }
                            });
                        }
                    })
                } else{
                    _that.props.dispatch({
                        type: 'theme/addInformation', data: allForm, callback: (data) => {
                            setAdding(false,0);
                            if (data.code === 200){
                                this.submitTranscode(this.props.add.transcode_data,data.data,3)
                                message.success('保存成功!');
                                _that.setState({
                                    add_information_id: data.data
                                });
                                // this.closeWindow();
                                if (idss === 1) {
                                    _that.props.dispatch({
                                        type: 'theme/getAuditVideo', data: {
                                            status: 1,
                                            information_ids: [data.data]
                                        }
                                    });
                                    _that.closeWindow();
                                }

                            }

                        }
                    });

                }


            } else if (this.props.theme.params.class && (this.props.theme.params.class == 'theme_edit' || this.state.add_information_id > 0) ) { //专题资讯修改

                allForm.information_id = this.state.add_information_id ? this.state.add_information_id : this.props.theme.params.theme_id;
                let _that = this;
                if (this.props.add.configJson.sensitivewordsSwitch){
                    validateSensitive({'content':allForm['content']}).then((res) => {

                        if (res.data.code === 500) {

                            confirm({
                                title: '存在敏感词，确认继续保存吗',
                                content: '敏感词：'+res.data.data,
                                onOk() {
                                    // console.log('OK');
                                    _that.props.dispatch({ type: 'add/updateInformation', data: allForm, callback:(code) => {

                                            if (code === 200) {
                                                this.submitTranscode(this.props.add.transcode_data,allForm.information_id,3)
                                                message.success('保存成功!');
                                                if (idss === 1) {

                                                    _that.props.dispatch({
                                                        type: 'theme/getAuditVideo', data: {
                                                            status: 1,
                                                            information_ids: [allForm.information_id]
                                                        }
                                                    });
                                                    _that.closeWindow();
                                                }


                                            }
                                        }
                                    });
                                },
                                onCancel() {

                                },
                            });
                        }else{
                            _that.props.dispatch({ type: 'add/updateInformation', data: allForm, callback:(code) => {

                                    if (code === 200) {
                                        this.submitTranscode(this.props.add.transcode_data,allForm.information_id,3)
                                        message.success('保存成功!');
                                        if (idss === 1) {

                                            _that.props.dispatch({
                                                type: 'theme/getAuditVideo', data: {
                                                    status: 1,
                                                    information_ids: [allForm.information_id]
                                                }
                                            });
                                            _that.closeWindow();
                                        }


                                    }
                                }
                            });
                        }
                    })
                }else{
                    _that.props.dispatch({ type: 'add/updateInformation', data: allForm, callback:(code) => {

                            if (code === 200) {
                                this.submitTranscode(this.props.add.transcode_data,allForm.information_id,3)
                                message.success('保存成功!');
                                if (idss === 1) {

                                    _that.props.dispatch({
                                        type: 'theme/getAuditVideo', data: {
                                            status: 1,
                                            information_ids: [allForm.information_id]
                                        }
                                    });
                                    _that.closeWindow();
                                }


                            }
                        }
                    });
                }


            } else {
                if (this.state.add_information_id > 0){
                    if (idss > 0){
                        this.toShenHe();
                    }else{
                        this.editSave();
                    }
                    return;
                }
                if (getAdding()){
                    return false;
                }
                setAdding(true,0);
                allForm.user_name = this.state.user_name;
                allForm.token = token;
                let _that = this;
                if (this.props.add.configJson.sensitivewordsSwitch){
                    validateSensitive({'content':allForm['content']}).then((res) => {

                        if (res.data.code === 500) {

                            confirm({
                                title: '存在敏感词，确认继续保存吗',
                                content: '敏感词：'+res.data.data,
                                onOk() {

                                    _that.props.dispatch({
                                        type: 'add/addInformation', data: allForm, callback: (data) => {
                                            // this.closeWindow();
                                            setAdding(false,0);
                                            if (data.code === 200){
                                                this.submitTranscode(this.props.add.transcode_data,data.data,2)
                                                message.success('保存成功!');
                                                this.addInformation(allForm,data.data)
                                                _that.setState({
                                                    add_information_id: data.data
                                                });

                                                if (idss === 1) {

                                                    _that.props.dispatch({
                                                        type: 'add/getAuditVideo', data: {
                                                            status: 1,
                                                            information_ids: [data.data]
                                                        }
                                                    });
                                                    _that.closeWindow();
                                                }
                                            }

                                        }
                                    });
                                },
                                onCancel() {
                                    setAdding(false,0);

                                },
                            });

                        }else{

                            _that.props.dispatch({
                                type: 'add/addInformation', data: allForm, callback: (data) => {
                                    // this.closeWindow();
                                    setAdding(false,0);
                                    if (data.code === 200){
                                        this.submitTranscode(this.props.add.transcode_data,data.data,2)
                                        message.success('保存成功!');
                                        this.addInformation(allForm,data.data)
                                        _that.setState({
                                            add_information_id: data.data
                                        });

                                        if (idss === 1) {

                                            _that.props.dispatch({
                                                type: 'add/getAuditVideo', data: {
                                                    status: 1,
                                                    information_ids: [data.data]
                                                }
                                            });
                                            _that.closeWindow();
                                        }
                                    }

                                }
                            });
                        }
                    })
                } else{
                    _that.props.dispatch({
                        type: 'add/addInformation', data: allForm, callback: (data) => {
                            // this.closeWindow();
                            setAdding(false,0);
                            if (data.code === 200){
                                this.submitTranscode(this.props.add.transcode_data,data.data,2)
                                message.success('保存成功!');
                                this.addInformation(allForm,data.data)
                                _that.setState({
                                    add_information_id: data.data
                                });

                                if (idss === 1) {

                                    _that.props.dispatch({
                                        type: 'add/getAuditVideo', data: {
                                            status: 1,
                                            information_ids: [data.data]
                                        }
                                    });
                                    _that.closeWindow();
                                }
                            }

                        }
                    });
                }


            }
        }
    }

    /*
    推送到微信
     */
    pushWeixin = () => {
        if (this.props.add.activeKey != '1') {
            message.error('只能推送文章');
            return;
        }
        let leftForm = this.props.getLeft();
        let rightForm = this.props.getRight();
        let allForm = {};

        // console.log(leftForm, rightForm)
        if (leftForm && rightForm) {
            Object.assign(allForm, leftForm, rightForm);
            if (!allForm['weixin_mpid'] || allForm['weixin_mpid'].length == 0){
                message.error('请选择推送的公众号');
                return;
            }
            let push_data = {
                'attachments':allForm['information_img'],
                'title':allForm['information_title'],
                'summary':allForm['intro'],
                'content':allForm['content'],
                'reporter':allForm['create_user'],
                'mpid':allForm['weixin_mpid']
            }
            let wx_url = this.props.add.configJson.weixinUrl;
            let hideConfig = message.loading('推送中...', 0);
            weixinPush(wx_url,push_data).then((res) => {
                setTimeout(hideConfig, 100);
                if (res.data.code === 200) {
                    message.success('推送成功');
                }else{
                    message.error('推送失败');
                }
            })
        }
    }

    /**
     * 编辑  提交审核
     */
    toShenHe = () => {
        let leftForm = this.props.getLeft()
        let rightForm = this.props.getRight()
        let allForm = {}
        if (leftForm && rightForm) {
            Object.assign(allForm, leftForm, rightForm);
            console.log({allForm});

            allForm.key_words = allForm.key_words&&Array.isArray(allForm.key_words) ? allForm.key_words.join('|') : allForm.key_words;
            allForm.tag = allForm.tag&&Array.isArray(allForm.tag) ? allForm.tag.join('|') : allForm.tag;

            allForm["information_id"] = this.props.id ? this.props.id : this.state.add_information_id;
            let _that = this;
            if (this.props.add.configJson.sensitivewordsSwitch) {
                validateSensitive({'content':allForm['content']}).then((res) => {

                    if (res.data.code === 500) {

                        confirm({
                            title: '存在敏感词，确认继续保存吗',
                            content: '敏感词：'+ res.data.data,
                            onOk() {
                                _that.props.dispatch({ type: 'add/editInformation', data: allForm, toShenHe: 1,callback:(code) => {
                                        if (code === 200) {
                                            this.submitTranscode(this.props.add.transcode_data,allForm["information_id"],2)
                                            this.addInformation(allForm,allForm["information_id"],1)
                                            _that.props.dispatch({         
                                                type: 'add/getAuditVideo', data: {
                                                    status: 1,
                                                    information_ids: [allForm["information_id"]]
                                                }
                                            });
                                            _that.closeWindow();
                                        }
                                    }      
                                });

                            },
                            onCancel() {
                               

                            },
                        });

                    }else{
                        _that.props.dispatch({ type: 'add/editInformation', data: allForm, toShenHe: 1,callback:(code) => {
                                if (code === 200) {
                                    this.submitTranscode(this.props.add.transcode_data,allForm["information_id"],2)
                                    this.addInformation(allForm,allForm["information_id"],1)
                                    _that.props.dispatch({
                                        type: 'add/getAuditVideo', data: {
                                            status: 1,
                                            information_ids: [allForm["information_id"]]
                                        }
                                    });
                                    _that.closeWindow();
                                }
                            }
                        });

                    }
                })

            }else{
                _that.props.dispatch({ type: 'add/editInformation', data: allForm, toShenHe: 1,callback:(code) => {
                        if (code === 200) {
                            this.submitTranscode(this.props.add.transcode_data,allForm["information_id"],2)
                            _that.props.dispatch({
                                type: 'add/getAuditVideo', data: {
                                    status: 1,
                                    information_ids: [allForm["information_id"]]
                                }
                            });
                            this.addInformation(allForm,allForm["information_id"],1)
                            _that.closeWindow();
                        }
                    }
                });
            }


        }
    }


    closeWindow = ()=>{
        message.success('1秒后自动关闭页面~');
        setTimeout(() => {
            window.close();
        }, 1000);
    }

    /**
     * 修改
     */
    editSave = () => {
        let leftForm = this.props.getLeft()
        let rightForm = this.props.getRight()
        // console.log(rightForm, 'rightForm')
        let allForm = {}
        if (leftForm && rightForm) {
            Object.assign(allForm, leftForm, rightForm);
            allForm["information_id"] = this.props.id ? this.props.id : this.state.add_information_id;
            console.log({allForm});
            allForm.key_words = allForm.key_words&&Array.isArray(allForm.key_words) ? allForm.key_words.join('|') : allForm.key_words;
            allForm.tag = allForm.tag&&Array.isArray(allForm.tag) ? allForm.tag.join('|') : allForm.tag;
            let _that = this;
            if (this.props.add.configJson.sensitivewordsSwitch){
                validateSensitive({'content':allForm['content']}).then((res) => {

                    if (res.data.code === 500) {

                        confirm({
                            title: '存在敏感词，确认继续保存吗',
                            content: '敏感词：'+res.data.data,
                            onOk() {
                                _that.props.dispatch({ type: 'add/editInformation', data: allForm,toShenHe: 0,callback:(code) => {
                                        if (code === 200) {
                                            this.submitTranscode(this.props.add.transcode_data,allForm["information_id"],2)
                                            message.success('保存成功!');
                                            // this.closeWindow();
                                        }
                                    }
                                });
                                this.addInformation(allForm,allForm["information_id"],1)

                            },
                            onCancel() {

                            },
                        });

                    }else{
                        _that.props.dispatch({ type: 'add/editInformation', data: allForm,toShenHe: 0,callback:(code) => {
                                if (code === 200) {
                                    this.submitTranscode(this.props.add.transcode_data,allForm["information_id"],2)
                                    message.success('保存成功!');
                                    this.addInformation(allForm,allForm["information_id"],1)

                                    // this.closeWindow();
                                }
                            }
                        });
                    }
                })

            }else {
                _that.props.dispatch({ type: 'add/editInformation', data: allForm,toShenHe: 0,callback:(code) => {
                        if (code === 200) {
                            this.submitTranscode(this.props.add.transcode_data,allForm["information_id"],2)
                            message.success('保存成功!');
                            this.addInformation(allForm,allForm["information_id"])

                            // this.closeWindow();
                        }
                    }
                });
            }




            // localStorage.setItem('treeSelectedKeys',extra.triggerNode.props.eventKey);

        }
    }

    //提交转码任务
    submitTranscode = (postData,id,type) => {
        if (postData && postData.length > 0){
            postData.forEach(item => {
                item.article_id = item.video_id;
                item.type = 1;
                if (type == 2){
                    item.information_id = id;
                }
                if (type == 3){
                    item.theme_information_id = id;
                }
                transcode(item);

            });
            this.props.dispatch({
                type: 'add/setTranscodeData',
                data: []
            })

        }

    }

    render() {
        let size = 'large';
        return (
            <div className="Footer">
                {this.props.type==='edit'?
                    <Button className='mon_text_btn' type="primary" size={size} onClick={throttle(this.toShenHe,1000)}>ᠬᠢᠨᠠᠯᠲᠠ᠎ᠳᠤ ᠲᠤᠰᠢᠶᠠᠬᠤ</Button>
                    :
                    <Button className='mon_wrap_text_btn' type="primary" onClick={()=>this.submitForm(1)} size={size} >ᠬᠢᠨᠠᠯᠲᠠ᠎ᠳᠤ ᠲᠤᠰᠢᠶᠠᠬᠤ</Button>
                }

                {this.props.type === 'edit' ?
                     <Button className='mon_wrap_text_btn' size={size} onClick={throttle(this.editSave,1000)}>ᠡᠬᠡ ᠨᠣᠣᠷᠠᠭ ᠬᠠᠳᠠᠭᠠᠯᠠᠬᠤ</Button>
                    :
                     <Button className='mon_wrap_text_btn' size={size} onClick={throttle(this.submitForm,1000)}>ᠡᠬᠡ ᠨᠣᠣᠷᠠᠭ ᠬᠠᠳᠠᠭᠠᠯᠠᠬᠤ</Button>
                }


                {/* <Button size={size}>发布</Button> */}
                <Popconfirm className="FooterPop" placement="topLeft" icon={null} title="确认要重置吗?" onConfirm={this.reSet} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button className='mon_wrap_text_btn' size={size} >ᠳᠠᠬᠢᠵᠦ ᠲᠣᠬᠢᠷᠠᠭᠤᠯᠬᠤ</Button>
                </Popconfirm>

                <Popconfirm className="FooterPop" placement="topLeft" icon={null} title="请确认稿件已全部保存，返回列表界面?" onConfirm={this.confirm} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button className='mon_wrap_text_btn' size={size}>ᠬᠠᠭᠠᠬᠤ</Button>
                </Popconfirm>
                {this.props.add.configJson.weixinPushSwitch && this.props.add.configJson.weixinUrl?
                    <Popconfirm className="FooterPop" placement="topLeft" icon={null} title="请确认稿件已保存，确定推送?" onConfirm={this.pushWeixin} onCancel={() => { }} okText="确定" cancelText="取消">
                        <Button className='mon_wrap_text_btn' size={size}>ᠬᠦᠷᠭᠡᠬᠦ</Button>
                    </Popconfirm>
                    :
                    ''
                }
            </div>
        )
    }
}
